<template>
    <!-- v2.5新版本的编辑个人资料页 -->
    <view>
        <view class="title" style="padding: 25rpx 0">电子发票与纸质发票具有同等效力</view>
        <view>
            <van-cell title="抬头类型">
                <van-radio-group v-model="radio" @change="onChange">
                    <van-radio style="margin-right: 25rpx" name="1">公司抬头</van-radio>
                    <van-radio name="2">个人/非企业抬头</van-radio>
                </van-radio-group>
            </van-cell>
            <!-- <van-cell title="空间类型"  size="large" is-link model:value="{{spaceTypeChoose?spaceTypeChoose:'请选择'}}"
      bind:click="showPopup" data-type="spaceType" /> -->
            <van-cell title="发票抬头">
                <input type="text" placeholder="点击填写发票抬头" confirm-type="done" v-model="billName" />
            </van-cell>
            <van-cell title="发票税号" v-if="radio == 1">
                <input type="text" placeholder="点击填写纳税人识别号" confirm-type="done" v-model="billId" />
            </van-cell>
            <van-cell title="发票内容">
                <input type="text" disabled confirm-type="done" value="停车费" />
            </van-cell>
            <van-cell title="开票金额">
                <input type="text" placeholder="点击填写发票税号" disabled :value="fee" />
            </van-cell>
        </view>

        <view class="tip" style="padding: 26rpx">接收方式</view>
        <input type="text" class="emailInput" style="padding: 26rpx" placeholder="点击填写邮箱地址" confirm-type="done" v-model="emailAddress" @confirm="changeName" />

        <view class="out-btn" @tap="submit">提交</view>
        <!-- 单选弹窗 -->
        <van-popup round v-model="isShowPopup" @close="onClosePicker" position="bottom" custom-style="height: 45%">
            <van-picker
                :columns="columnsData"
                :data-type="popupType"
                :value-key="columnsName"
                show-toolbar
                :title="popupTitle"
                @change="onChange($event, { type: popupType })"
                :default-index="columnsIndex"
                @cancel="onClosePicker($event, { type: popupType })"
                @confirm="onConfirmPicker($event, { type: popupType })"
            />
        </van-popup>
    </view>
</template>

<script>
// pages/newChangeUser/newChangeUser.js
import util from './../../utils/util.js';
import api from './../../utils/api.js';
export default {
    data() {
        return {
            billNo: [],
            billName: '',
            emailAddress: '',
            billId: '',
            spaceTypeChoose: '',
            spaceTypeChooseKey: '',
            radio: '1',
            username: '',
            phoneNumber: '',
            plateNos: '',
            faceImageUrl: '',
            url: '',

            //头像没改就传空，改了就需要重置为该路径
            fileList: '',

            parkingCode: '',
            fee: '',
            isShowPopup: '',
            popupTitle: '',
            popupType: '',
            columnsData: '',
            columnsName: '',
            columnsIndex: 0
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.setData({
            parkingCode: options.parkingCode,
            fee: options.fee,
            billNo: options.billNos
        });
        uni.showLoading({
            title: '加载中'
        });
        this.getPersonInfoByIndentityId();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        showPopup(event) {
            let type = event.target.dataset.type;
            this.setPopStatus(type, true);
        },

        onClosePicker(event, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(event, _dataset);
            /* ---处理dataset end--- */
            let type = event.target.dataset.type;
            this.setPopStatus(type, false);
        },

        setPopStatus(type, data) {
            var that = this;

            switch (type) {
                case 'spaceType':
                    this.setData({
                        isShowPopup: data,
                        popupTitle: '空间类型',
                        popupType: 'spaceType',
                        columnsData: this.spaceList,
                        columnsName: 'value',
                        columnsIndex: 0
                    });
                    break;
            }
        },

        onConfirmPicker(event, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(event, _dataset);
            /* ---处理dataset end--- */
            console.log(event);
            let type = event.target.dataset.type;
            const { value } = event.detail;

            switch (type) {
                case 'spaceType':
                    this.setData({
                        spaceTypeChoose: value.value,
                        spaceTypeChooseKey: value.key
                    });
                    break;
            }

            this.setData({
                isShowPopup: false
            });
            this.getList();
        },

        //radio改变
        onChange(event, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(event, _dataset);
            /* ---处理dataset end--- */
            this.setData({
                radio: event.detail
            });
        },

        //获取个人资料
        getPersonInfoByIndentityId() {
            uni.hideLoading();
            let value = uni.getStorageSync('unionId');
            util.request(api.PersonInfoByIndentityId + '?personUnionId=' + value, 'get').then((res) => {
                if (res.code == 0) {
                    var pat = /(\d{3})\d*(\d{4})/;
                    this.setData({
                        username: res.data.name,
                        // phoneNumber: res.data.phoneNumber.replace(pat, "$1****$2"),
                        phoneNumber: res.data.phoneNumber,
                        plateNos: res.data.plateNos
                    });
                } //头像转化

                if (res.data.headImageUrl) {
                    util.request(api.getEncryPath + '?path=' + res.data.headImageUrl, '', 'POST').then((res) => {
                        this.setData({
                            faceImageUrl: res
                        });
                    });
                }
            });
        },

        // 修改昵称--手机上点击完成按钮才触发
        changeName(e) {
            if (!e.detail.value.replaceAll(' ', '')) {
                uni.showToast({
                    title: '昵称不能为空',
                    icon: 'none'
                });
                return;
            }

            this.setData(
                {
                    username: e.detail.value
                },
                () => {
                    this.setupdateUser();
                }
            );
        },

        // 点击上传图片
        afterRead(event) {
            const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式

            var that = this; //坑1： this需要这么处理

            uni.uploadFile({
                url: api.vueUpload,
                filePath: file.url,
                name: 'file',
                formData: {
                    user: 'test'
                },
                header: {
                    Authorization: uni.getStorageSync('AUTHORIZATION') //如果需要token的话要传
                },

                success(res) {
                    var data = JSON.parse(res.data);
                    that.setData(
                        {
                            url: data.data
                        },
                        () => {
                            that.setupdateUser();
                        }
                    );

                    if (data.data) {
                        //这个步骤是为了展示上传的图片
                        util.request(api.getEncryPath + '?path=' + data.data, '', 'POST').then((res) => {
                            // that.setData({ fileList: [{ url: res }] });
                            that.setData({
                                faceImageUrl: res
                            });
                            uni.setStorageSync('faceImageUrl', res);
                        });
                    }
                }
            });
        },

        // 提交修改
        setupdateUser() {
            const identityId = uni.getStorageSync('identityId');
            const param = {
                loginName: uni.getStorageSync('phoneNumber'),
                name: this.username,
                url: this.url,
                plates: this.plateNos,
                identityId: identityId
            };
            util.request(api.updateUser, param, 'POST').then((res) => {
                if (res.code == 0) {
                    uni.showToast({
                        title: '修改成功',
                        icon: 'none'
                    });
                    uni.setStorage({
                        key: 'name',
                        data: this.username
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        },

        // 提交
        submit() {
            // var submitFlag=true;
            if (this.radio == 1) {
                //readio=2为公司
                console.log(1);

                if (!this.billName || !this.billId || !this.emailAddress) {
                    uni.showToast({
                        title: '请填写完整的信息',
                        icon: 'none'
                    });
                    return;
                }
            } else {
                //readio=2为个人
                if (!this.billName || !this.emailAddress) {
                    uni.showToast({
                        title: '请填写完整的信息',
                        icon: 'none'
                    });
                    return;
                }
            }

            var param = {};
            const unionId = uni.getStorageSync('unionId') || '';

            if (this.radio == 1) {
                //readio=2为公司
                param.unionId = unionId; //"e5ecc37c-dc0c-450a-ac96-e91c3349408b",//unionId

                param.taxNum = this.billId;
                param.name = this.billName;
                param.invoiceType = 1;
                param.email = this.emailAddress;
                param.billNoList = this.billNo.split(',');
                param.parkingCode = this.parkingCode;
            } else {
                //readio=2为个人
                param.unionId = unionId; //e5ecc37c-dc0c-450a-ac96-e91c3349408b

                param.taxNum = '';
                param.name = this.billName;
                param.invoiceType = 0;
                param.email = this.emailAddress;
                param.billNoList = this.billNo.split(',');
                param.parkingCode = this.parkingCode;
            }

            util.request(api.dealInvoice, param, 'POST').then((res) => {
                if (res.code == 0) {
                    uni.showModal({
                        title: '成功',
                        content: '电子发票开具完成后将发送至您预留的邮箱地址，请注意查收。',
                        success: function (result) {
                            if (result.confirm) {
                                uni.navigateBack({
                                    delta: 3
                                });
                            }
                        }
                    });
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
